<?php

namespace App\Http\Controllers;

use App\Models\Question;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class AnswerController extends Controller
{
    /**
     * 保存用户提交的答案
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request, $id)
    {
        /** @var User $user 考生 */
        $user = Auth::user();

        // 考试机会已用完（暂不限制）
        // if (! $user->canTest()) {
        //     return response()->json([
        //         'code' => '403',
        //         'message' => '您今天已参与过自测，请明天再来，感谢您的参与！',
        //     ]);
        // }

        // 考试
        $test = $user->currentTest();

        if (! $test) {
            return response()->json(['code' => '404', 'message' => '没有进行中的考试。']);
        }

        /** @var Question $question 考题 */
        $question = Question::getFromCache($id);

        if (! $question) {
            return response()->json(['code' => '404', 'message' => '未找到该考题。' . $id]);
        }

        $userAnswer = array_unique((array) $request->get('answer', []));

        sort($userAnswer);

        if (! $userAnswer) {
            return response()->json(['code' => '404', 'message' => '请选择答案。']);
        }

        // 提交答案
        try {
            /** @var Collection $answers */
            $answers = Cache::get('answer_for_user_' . $user->id . '_test_' . $test->id, collect());

            $answers->put($question->id, [
                'user_id' => $user->id,
                'test_id' => $test->id,
                'question_id' => $question->id,
                'answer' => $userAnswer,
                'is_right' => $userAnswer == $question->answer_array,
            ]);

            Cache::put('answer_for_user_' . $user->id . '_test_' . $test->id, $answers, 600);

            return response()->json(['code' => '200', 'message' => 'success']);
        } catch (\Exception $e) {
            Log::error('提交答案出错' . $e->getMessage(), $request->all());

            return response()->json(['code' => '500', 'message' => $e->getMessage()]);
        }
    }
}
